package com.ruowei.modules.member.service;

import com.alibaba.fastjson.JSONObject;
import com.ruowei.common.error.exception.CommonException;
import com.ruowei.config.ApplicationProperties;
import com.ruowei.modules.member.domain.Member;
import com.ruowei.modules.member.repository.MemberRepository;
import com.ruowei.modules.sys.utils.CommonUtils;
import com.ruowei.modules.sys.utils.HttpUtils;
import com.ruowei.modules.sys.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class MemberService {

    private final RedisUtil redisUtil;
    private final ApplicationProperties applicationProperties;
    private final MemberRepository memberRepository;

    public MemberService(RedisUtil redisUtil, ApplicationProperties applicationProperties, MemberRepository memberRepository) {
        this.redisUtil = redisUtil;
        this.applicationProperties = applicationProperties;
        this.memberRepository = memberRepository;
    }

    public String getOpenIdByCode(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> params = new HashMap<>();
        params.put("appid", applicationProperties.getAppId());
        params.put("secret", applicationProperties.getAppSecret());
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");
        String responseData = HttpUtils.get(url, params);
        JSONObject responseObj = JSONObject.parseObject(responseData);
        String openId = responseObj.getString("openid");
        Integer errorCode = responseObj.getInteger("errcode");
        if (errorCode != null && (!errorCode.equals(0) || StringUtils.isEmpty(openId))) {
            throw new CommonException("小程序登录凭证校验失败,错误信息" + responseObj.getString("errmsg"));
        }

        //双重加密
        String tokenMd5 = DigestUtils.md5Hex(openId);
        String appletToken = DigestUtils.sha1Hex(tokenMd5);
        Member member;
        if (!memberRepository.findByOpenId(openId).isPresent()) {
            member = new Member();
            member.setOpenId(openId);
            member.setAppletToken(appletToken);
            member.setCreateTime(Instant.now());
            member.setAvailablePoints(0);
            member.setGrowth(0);
            member.setHistoryPoints(0);
            member.setTotalConsumption(BigDecimal.ZERO);
            member.setLevel(0);
        } else {
            member = memberRepository.findByOpenId(openId).get();
            member.setAppletToken(appletToken);
        }
        memberRepository.save(member);
        //生成登录态 和openId绑定存到redis
        redisUtil.set(appletToken, openId);
        return appletToken;
    }
}
